/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package io.iec.edp.caf.multicontext.support;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

public class JarUtil {
    public static URL[] getJarPathFromPaths(List<String> paths){
        List<URL> urls = new ArrayList<>();
        paths.forEach(path->{
            URL[] arr = getJarPathFromDirPaths(path);
            urls.addAll(Arrays.asList(arr));
        });
        return urls.toArray(new URL[0]);
    }

    public static URL[] getJarPathFromDirPaths(String path) {
        try {
            List<URL> urlList = new ArrayList();

            String root = cleanupPath(handleUrl(path));
            if (!isAbsolutePath(root)) {
                throw new Exception("Unsupported URL:" + root);
            }

            File file = new File(root);
//            File filelibs = new File(file,"libs");
//            if (filelibs.isDirectory()) {
//                urlList.add(filelibs.toURI().toURL());
//                urlList.addAll(getClassFromPath(filelibs));
//            } else if (filelibs.getName().endsWith(".jar")) {
//                urlList.add(filelibs.toURI().toURL());
//            }else if(!filelibs.exists()){
//                urlList.add(file.toURI().toURL());
//                urlList.addAll(getClassFromPath(file));
//            }
            if (file.isDirectory()) {
                urlList.add(file.toURI().toURL());
                urlList.addAll(getClassFromPath(file));
            } else if (file.getName().endsWith(".jar")) {
                urlList.add(file.toURI().toURL());
            }

            return (URL[]) (new ArrayList(new HashSet(urlList))).toArray(new URL[0]);
        } catch (Exception var8) {
            throw new RuntimeException("internal error",var8);
        }
    }

    private static List<URL> getClassFromPath(File rootFile) throws MalformedURLException {
        List<URL> result = new ArrayList();
        File[] var2 = rootFile.listFiles();
        int var3 = var2.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            File file = var2[var4];
            if (file.isDirectory()) {
                result.addAll(getClassFromPath(file));
            } else if (file.getName().toLowerCase().endsWith(".jar")) {
                result.add(file.toURI().toURL());
            }
        }

        return result;
    }

    private static boolean isAbsolutePath(String root) {
        return root.contains(":") || root.startsWith("/");
    }

    private static String handleUrl(String path) throws UnsupportedEncodingException {
        if (path.startsWith("jar:file:") || path.startsWith("file:")) {
            path = URLDecoder.decode(path, "UTF-8");
            if (path.startsWith("file:")) {
                path = path.substring("file:".length());
                if (path.startsWith("//")) {
                    path = path.substring(2);
                }
            }
        }

        return path;
    }

    private static String cleanupPath(String path) {
        path = path.trim();
        if (path.startsWith("./")) {
            path = path.substring(2);
        }

        String lowerCasePath = path.toLowerCase(Locale.ENGLISH);
        if (!lowerCasePath.endsWith(".jar") && !lowerCasePath.endsWith(".zip")) {
            if (path.endsWith("/*")) {
                path = path.substring(0, path.length() - 1);
            } else if (!path.endsWith("/") && !path.equals(".")) {
                path = path + "/";
            }

            return path;
        } else {
            return path;
        }
    }
}